package edu.dut.personal_scheduler.ui;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.TextView;
import edu.dut.personal_scheduler.R;
import edu.dut.personal_scheduler.ui.fragment.AbsFragment;
import edu.dut.personal_scheduler.ui.fragment.LoginFragment;

public class MainActivity extends FragmentActivity {

	private TextView pageTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		pageTitle = (TextView) findViewById(R.id.textView_mainTitle);

		startFragment(new LoginFragment(), false);
	}

	public void startFragment(AbsFragment iFragment, boolean addBackStack) {
		FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
		mTransaction.replace(R.id.fLayout_main, iFragment);
		if (addBackStack) {
			mTransaction.addToBackStack(null);
		}
		if (pageTitle != null) {
			pageTitle.setText(iFragment.getPageTitle());
		}
		mTransaction.commitAllowingStateLoss();
	}

	@Override
	//Count Overflow
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			int fragmentCount = getSupportFragmentManager().getBackStackEntryCount();
			if (fragmentCount > 0) {
				Fragment curRawFragment = getSupportFragmentManager().getFragments().get(fragmentCount - 1);
				if (curRawFragment != null && pageTitle != null && curRawFragment instanceof AbsFragment) {
					pageTitle.setText(((AbsFragment) curRawFragment).getPageTitle());
				}
			}
		}
		return super.onKeyDown(keyCode, event);
	}

}
